package wty;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.DefaultCategoryDataset;
import javax.swing.*;
import java.sql.*;

public class DatabaseChart extends JFrame {

    public DatabaseChart() {
        super("Database Chart");

        // 创建数据集
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        // 数据库连接和数据检索
        String url = "jdbc:mysql://localhost:3306/project";
        String user = "root";
        String password = "root";

        try (Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement();
             //该查询从 consumer 表中获取每个 category 的消费总和（SUM(number)），并按 category 分组。
             ResultSet rs = stmt.executeQuery("SELECT category, SUM(number) AS total FROM consumer GROUP BY category")) {

            while (rs.next()) {
                String category = rs.getString("category");
                double total = rs.getDouble("total");
                //第二个是系列名称，多个时将会按照颜色不同来区分
                dataset.addValue(total, "Consumption", category);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Database error: " + e.getMessage());
        }

        // 创建图表
        JFreeChart chart = ChartFactory.createBarChart(
                "Consumption Statistics",
                "Category",
                "Total",
                dataset,
                org.jfree.chart.plot.PlotOrientation.VERTICAL, // 这里是垂直方向
                false, // 不显示图例
                true, // 当鼠标悬停在柱子上时会显示数据值
                false //  不显示 URL
        );

        // 添加图表到面板
        ChartPanel chartPanel = new ChartPanel(chart);
        setContentPane(chartPanel);
    }

//    public static void main(String[] args) {
//        SwingUtilities.invokeLater(() -> {
//            DatabaseChart demo = new DatabaseChart();
//            demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//            demo.pack();
//            demo.setLocationRelativeTo(null);
//            demo.setVisible(true);
//        });
//    }
}
